/**
 * 上传文件到“七牛云-CDN”
 * 
 * 需要安装 qshell，并设置 %Path%
 * account.json 配置文件在 C:\Users\Administrator\.qshell 目录下
 * 用 cmd 打开运行
 */

const path = require('path')
const { exec } = require('shelljs')
const fs = require('fs')

const qnConf = {
    "name": "xxx",
    "ak": "xxx-xxx",
    "sk": "xx-xx-xxx",
    "src_dir": `${path.resolve(process.cwd(), './dist-out').replace(/\\/g, '/')}`,
    "bucket": "note-asset",
    "key_prefix": "",
    "overwrite": true,
    "rescan_local": true,
    "log_file": "qnupload.log",
    "file_type": 0
}

function qiniuUploader(qnConf) {
    console.log('>>> 登陆七牛...')
    exec(`qshell account ${qnConf.ak} ${qnConf.sk} ${qnConf.name}`)

    console.log('>>> 隐藏 ak sk...')
    delete qnConf.ak
    delete qnConf.sk

    console.log('>>> 生成七牛配置文件...')
    fs.writeFile(process.cwd() + '/qn.config.json', JSON.stringify(qnConf, null, 2), (err) => {
        if (err)
            return console.log(chalk.red(err))

        console.log('>>> 查找七牛上此项目现有文件...')
        exec(`qshell listbucket ${qnConf.bucket} ${qnConf.key_prefix} qnlist.txt`)

        console.log('>>> 删除此项目现有文件...')
        exec(`qshell batchdelete -force ${qnConf.bucket} qnlist.txt`)

        console.log('>>> 上传至 cdn...')
        exec(`qshell qupload qn.config.json`)
    })
}

console.info(`cdn 开始 【${new Date().toLocaleTimeString()}】`)

qiniuUploader(qnConf)

console.info(`cdn 结束 【${new Date().toLocaleTimeString()}】`)